package com.party.web.web.controller.member;

import com.google.common.collect.Lists;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.utils.LangUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.YesNoStatus;
import com.party.core.model.commune.CMoment;
import com.party.core.model.commune.MomentType;
import com.party.core.model.member.Member;
import com.party.core.model.member.MemberGroup;
import com.party.core.service.commune.ICMomentService;
import com.party.core.service.cos.CosBizService;
import com.party.core.service.dynamic.IDypicsService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.member.IMemberService;
import com.party.web.biz.file.FileBizService;
import com.party.web.biz.member.CMomentBizService;
import com.party.web.utils.RealmUtils;
import com.party.web.web.dto.AjaxResult;
import com.party.web.web.dto.input.common.CommonInput;
import com.party.web.web.dto.input.member.CMomentInput;
import com.party.web.web.dto.output.member.CMomentOutput;
import com.party.web.web.security.CurrentUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

/**
 * @program: party
 * @description: 动态控制器
 * @author: Hua Qunhao
 * @create: 2019-12-18 16:07
 **/
@Controller
@RequestMapping(value = "member/moment")
public class MomentController {

    @Autowired
    private ICMomentService momentService;
    @Autowired
    private IMemberGroupService memberGroupService;
    @Autowired
    private CMomentBizService momentBizService;
    @Autowired
    private IDypicsService dypicsService;
    @Autowired
    private IMemberService memberService;
    @Autowired
    private CosBizService cosBizService;
    @Autowired
    private FileBizService fileBizService;


    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * @Description: 动态列表
     * @Param: [moment, input, page]
     * @return: org.springframework.web.servlet.ModelAndView
     * @Author: Hua Qunhao
     * @Date: 2019/12/18
     */
    @RequestMapping("/list")
    public ModelAndView list(CMomentInput moment, CommonInput input, Page page) {
        page.setLimit(20);
        ModelAndView mv = new ModelAndView("member/moment/momentList");

        Map<String, Object> params = CommonInput.appendParams(input);
        if (null != params.get("startDate")) {
            input.setCreateStart(params.get("startDate").toString().substring(0, "2018-05-04".length()));
        }
        if (null != params.get("endDate")) {
            input.setCreateEnd(params.get("endDate").toString().substring(0, "2018-05-04".length()));
        }
        mv.addObject("input", input);

        CurrentUser currentUser = RealmUtils.getNewCurrentUser();
        params.put("isSelectMemberGroup", false);
        List<String> orgIds = Lists.newArrayList();
        List<MemberGroup> memberGroupList = new ArrayList<>();
        if (!Constant.MEMBER_XZGSADMIN.equals(currentUser.getType())) {
            if (!currentUser.isChild()) {
                memberGroupList = memberGroupService.getChildWithMyAndName(currentUser.getId());
                orgIds = LangUtils.transform(memberGroupList, input1 -> input1.getId());
            } else {
                orgIds.add(currentUser.getId());
                orgIds.add(currentUser.getPartnerId());
            }
        }else{
            memberGroupList = memberGroupService.queryAdminBranchAndXZGSList(currentUser.getId(),currentUser.getPartnerId());
        }
        if (StringUtils.isNotEmpty(moment.getMemberGroupId())) {
            orgIds = new ArrayList<>();
            orgIds.add(moment.getMemberGroupId());
            params.put("isSelectMemberGroup", true);
        }
        params.put("orgIds", orgIds);
        params.put("momentType", moment.getMomentType());
        params.put("content", moment.getContent());

        if (StringUtils.isNotEmpty(moment.getMemberName())) {
            List<Map<String, Object>> list = memberService.findPartnerMemberByPhoneOrName2("realName", moment.getMemberName().trim(), Member.MEMBER_PERSONAL, orgIds);
            List<String> memberIds = LangUtils.transform(list, input1 -> input1.get("id").toString());
            if(memberIds.size()>0){
                params.put("memberIds", memberIds);
            }
        }

        List<CMoment> cMoments = momentService.webListPage(params, page);
        List<CMomentOutput> outputs = LangUtils.transform(cMoments, cMoment -> {
            CMomentOutput output = CMomentOutput.transform(cMoment);
            if (StringUtils.isNotEmpty(cMoment.getPics())) {
                String[] split = cMoment.getPics().split("\\|");
                output.setPicList(Arrays.asList(split));
            }
            //发布者
            String memberLogo = "";
            String memberName = "";
            MemberGroup memberGroup = memberGroupService.get(cMoment.getCreateBy());
            if(memberGroup!=null){
                memberLogo = memberGroup.getLogo();
                memberName = memberGroup.getRealname();
            }
            if (StringUtils.isNotEmpty(cMoment.getMemberId())) {
                Member member = memberService.get(cMoment.getMemberId());
                if(null!=member){
                    memberLogo = member.getLogo();
                    memberName = member.getRealname();
                }
                output.setAnnouncerOrg(memberGroup.getRealname());
            }
            output.setMemberLogo(memberLogo);
            output.setMemberName(memberName);
            if (StringUtils.isNotEmpty(cMoment.getBusinessIds())) {
                String[] strings = cMoment.getBusinessIds().split(",");
                Set<String> set = new HashSet<String>(Arrays.asList(strings));
                List<Map<String, Object>> members = memberService.batchMemberList(set);
                output.setMembers(members);
            }

            return output;
        });

        mv.addObject("memberGroupList", memberGroupList);
        mv.addObject("cMoments", outputs);
        mv.addObject("momentTypes", MomentType.convertMap());
        mv.addObject("moment", moment);
        mv.addObject("page", page);
        mv.addObject("memberId", currentUser.getId());
        mv.addObject("isChild", currentUser.isChild());
        mv.addObject("isXzgsAdmin", currentUser.isXzgsAdmin());
        return mv;
    }


    /**
     * @Description:动态详情
     * @Param: [id]
     * @return: org.springframework.web.servlet.ModelAndView
     * @Author: Hua Qunhao
     * @Date: 2019/12/18
     */
    @RequestMapping("form")
    public ModelAndView form(String id) {
        ModelAndView mv = new ModelAndView("member/moment/momentForm");
        CurrentUser currentUser = RealmUtils.getNewCurrentUser();

        List<MemberGroup> memberGroups = new ArrayList<>();
        String memberId = currentUser.getId();
        if (!currentUser.isChild()) {
            memberGroups = memberGroupService.getChildWithMyAndName(currentUser.getId());
        }else if (currentUser.isXzgsAdmin()){
            memberGroups = memberGroupService.queryAdminBranchAndXZGSList(currentUser.getId(),currentUser.getPartnerId());
            memberId = currentUser.getPartnerId();
        }else{
            memberGroups = memberGroupService.getChildWithMyAndName(currentUser.getPartnerId());
        }
        if (StringUtils.isNotEmpty(id)) {
            CMoment cMoment = momentService.get(id);
            if (StringUtils.isNotEmpty(cMoment.getMemberId())) {
                Member member = memberService.get(cMoment.getMemberId());
                mv.addObject("member", member);
            }
            CMomentOutput output = CMomentOutput.transform(cMoment);
            if (StringUtils.isNotEmpty(cMoment.getPics())) {
                String[] split = cMoment.getPics().split("\\|");
                output.setPicList(Arrays.asList(split));
            }
            mv.addObject("cMoment", output);
            if (MomentType.MEMBER_JOIN.getCode() == output.getMomentType()) {
                List<Member> members = memberService.batchList(new HashSet<>(Arrays.asList(output.getBusinessIds().split(","))), null, null);
                mv.addObject("members", members);
            }
            memberId = output.getCreateBy();
        }
        mv.addObject("memberGroupList", memberGroups);
        mv.addObject("momentTypes", MomentType.convertMap());
        mv.addObject("memberId", memberId);
        mv.addObject("isChild", currentUser.isChild());
        mv.addObject("isXzgsAdmin", currentUser.isXzgsAdmin());
        return mv;
    }


    /**
     * @Description:动态保存
     * @Param: [moment]
     * @return: com.party.web.web.dto.AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/12/18
     */
    @ResponseBody
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @RequestMapping(value = "save")
    public AjaxResult save(CMomentInput moment) {
        if (StringUtils.isEmpty(moment.getContent())) {
            return AjaxResult.error("内容不能为空");
        }
        try {
            momentBizService.saveBizCMoment(moment);
        } catch (Exception e) {
            logger.info(e.getMessage());
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

    /**
     * @Description:动态删除
     * @Param: [moment]
     * @return: com.party.web.web.dto.AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/12/19
     */
    @ResponseBody
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @RequestMapping(value = "delete")
    public AjaxResult delete(String id) {
        if (StringUtils.isEmpty(id)) {
            return AjaxResult.error("内容不能为空");
        }
        boolean result = momentBizService.delBiz(id);
        if (result) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error("删除动态异常");
        }
    }

    /**
     * @Description:动态置底
     * @Param: [moment]
     * @return: com.party.web.web.dto.AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/12/19
     */
    @ResponseBody
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @RequestMapping(value = "topOperating")
    public AjaxResult topOperating(String id, Integer sign) {
        if (StringUtils.isEmpty(id)) {
            return AjaxResult.error("内容不能为空");
        }
        try {
            CMoment moment = momentService.get(id);
            if (YesNoStatus.NO.getCode() == sign) {
                moment.setIsTop(YesNoStatus.NO.getCode());
            } else {
                moment.setIsTop(YesNoStatus.YES.getCode());
            }
            momentService.update(moment);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return AjaxResult.error("动态置底操作异常");
        }
    }

    /**
     * @Description:全局操作
     * @Param: [moment]
     * @return: com.party.web.web.dto.AjaxResult
     * @Author: Hua Qunhao
     * @Date: 2019/12/19
     */
    @ResponseBody
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @RequestMapping(value = "globalOperating")
    public AjaxResult globalOperating(String id, Integer sign) {
        if (StringUtils.isEmpty(id)) {
            return AjaxResult.error("内容不能为空");
        }
        try {
            CMoment moment = momentService.get(id);
            if (YesNoStatus.NO.getCode() == sign) {
                moment.setIsDisplayAll(YesNoStatus.NO.getCode());
            } else {
                moment.setIsDisplayAll(YesNoStatus.YES.getCode());
            }
            momentService.update(moment);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error(e.getMessage());
            return AjaxResult.error("全局操作异常");
        }
    }
}
